package com.hr.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.hr.dao.DepartmentDao;
import com.hr.model.DepartmentModel;
/**
 * 部门DAO类
 * @author fazhen.zheng
 *
 */
@Repository
public class DepartmentDaoImpl implements DepartmentDao{
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public List<DepartmentModel> queryAll() {
		String sql = "select * from department";
		List<DepartmentModel> result = jdbcTemplate.query(sql,new BeanPropertyRowMapper<DepartmentModel>(DepartmentModel.class));

		return result;
	}
	@Override
	public void insert(DepartmentModel department) {
		String sql = "insert into department (code,parent_code,name,create_date,bz) values(?,?,?,?,?)";
		Object[] params = new Object[]{
				getNewCode(),
				department.getParent_code(),
				department.getName(),
				department.getCreate_date(),
				department.getBz()
		};
		jdbcTemplate.update(sql, params);
		
	}
	
	@Override
	public boolean delete(String code) {
		String sql = "delete from department where code=?";
		jdbcTemplate.update(sql, code);
		return true;
	}
	
	@Override
	public DepartmentModel queryByPrimaryKey(String code) {
		String sql = "select * from department where code=?";
		DepartmentModel departmentModel = jdbcTemplate.queryForObject(sql, new Object[]{code}, new BeanPropertyRowMapper<DepartmentModel>(DepartmentModel.class));
		return departmentModel;
	}
	@Override
	public boolean update(DepartmentModel department) {
		String sql = "update department set parent_code=?, name=?, bz=? where code=?";
		Object[] params = new Object[]{
				department.getParent_code(),
				department.getName(),
				department.getBz(),
				department.getCode()
		};
		jdbcTemplate.update(sql, params);
		return true;
	}
	
	/**
	 * 自定生成部门编号
	 * @return
	 */
	private String getNewCode(){
		String code="001";
		code = jdbcTemplate.queryForObject("select max(code) from department", String.class);
		if(code==null)
			return "001";
		int num = Integer.parseInt(code);
		num++;
		if(num<10)
			code="00"+num;
		else if(num<100)
			code="0"+num;
		else
			code = ""+num;
		return code;
	}
}
